import re
import sqlparse

def extract_fields_from_select(sql):
    # 正则表达式匹配SELECT语句中的字段名
    # 这个正则表达式假设字段名不包含特殊字符，并且没有使用函数或计算
    pattern = r'SELECT\s+(.*?)\s+FROM'
    match = re.search(pattern, sql, re.IGNORECASE)
    
    if match:
        # 分割字段名，假设字段名由逗号分隔
        fields = match.group(1).split(',')
        # 清理字段名中的空白字符
        fields = [field.strip() for field in fields]
        return fields
    else:
        return None
    
def extract_table_name_from_from(sql):
    pattern = r'FROM\s+(\w+)'
    match = re.search(pattern, sql, re.IGNORECASE)
    
    if match:
        return match.group(1)
    else:
        return None
    
def parse(sql):
    stmts = sqlparse.parse(sql)[0].tokens

    cols = []
    tbls = []
    froms = []
    wheres = []
    last_key = ''
    for stmt in stmts:
        if stmt.value == 'INSERT' or stmt.value == 'SELECT' or stmt.value == 'FROM':
            last_key = stmt.value
        # 剔除空格和换行
        if stmt.ttype is sqlparse.tokens.Text.Whitespace:
            continue
        # 关键字
        elif stmt.ttype is sqlparse.tokens.Keyword.DML:
            dml = stmt.value
            last_key = dml
        # 字段
        elif isinstance(stmt, sqlparse.sql.IdentifierList):
            # 判断上一个是什么类型
            if last_key == 'SELECT':
                for identifier in stmt.get_identifiers():
                    col_name = identifier.value
                    if re.search('AS', col_name, re.I):
                        col_name = re.search('AS (.*)', col_name, re.I).group(1).strip()
                    cols.append(col_name)
            elif last_key == 'FROM':
                for identifier in stmt.get_identifiers():
                    froms.append(identifier.value)
            else:
                for identifier in stmt.get_identifiers():
                    tbls.append(identifier.value)
        elif isinstance(stmt, sqlparse.sql.Identifier):
            if last_key == 'SELECT':
                cols.append(stmt.value)
            elif last_key == 'FROM':
                froms.append(stmt.value)
            else:
                tbls.append(stmt.value)
        elif isinstance(stmt, sqlparse.sql.Where):
            wheres.append(stmt.value)
        # 表名
    # print("cols:", cols)
    # print("tbls:", tbls)
    # print("froms:", froms)
    # print("wheres:", wheres)
    return tbls,cols,froms,wheres

def sql2bql(input):
    table_name=extract_table_name_from_from(input)
    output=input.replace(table_name,f"{table_name}.{table_name}")
    _,cols,_,_=parse(input)
    
    for field in cols:
        output=output.replace(field,f"{table_name}.{field}")
        
    
    return output